#!/usr/bin/env python3
"""
调试PV连接时序对数据获取的影响
"""

import epics
import time
import numpy as np

def test_pv_timing():
    """测试PV连接时序"""
    
    pv_name = "iLinac_007:BPM6:triggerAmp3_volt"
    print(f"测试PV: {pv_name}")
    
    print("\n=== 测试1: 模拟bmp.py的连接方式 ===")
    # 模拟bmp.py的连接方式
    pv1 = epics.PV(pv_name, connection_timeout=5.0)
    
    # 等待连接完成
    if pv1.wait_for_connection(timeout=5.0):
        print("✓ PV连接成功")
        
        # 立即获取数据（模拟bmp.py的行为）
        print("立即获取数据:")
        data1 = pv1.get()
        print(f"  数据类型: {type(data1)}")
        print(f"  数据值: {data1}")
        
        # 等待一段时间后再获取
        print("\n等待3秒后再获取:")
        time.sleep(3)
        data2 = pv1.get()
        print(f"  数据类型: {type(data2)}")
        print(f"  数据值: {data2}")
        if hasattr(data2, '__len__') and not isinstance(data2, str):
            print(f"  数据长度: {len(data2)}")
        
        # 强制刷新PV缓存
        print("\n强制刷新PV缓存后获取:")
        pv1.get(use_monitor=False)  # 强制从IOC获取最新数据
        data3 = pv1.get()
        print(f"  数据类型: {type(data3)}")
        print(f"  数据值: {data3}")
        if hasattr(data3, '__len__') and not isinstance(data3, str):
            print(f"  数据长度: {len(data3)}")
    else:
        print("✗ PV连接失败")
    
    print("\n=== 测试2: 模拟test_amp3_signal.py的连接方式 ===")
    # 模拟test_amp3_signal.py的连接方式
    pv2 = epics.PV(pv_name)
    time.sleep(2)  # 等待连接
    
    if pv2.connected:
        print("✓ PV连接成功")
        data4 = pv2.get()
        print(f"  数据类型: {type(data4)}")
        print(f"  数据值: {data4}")
        if hasattr(data4, '__len__') and not isinstance(data4, str):
            print(f"  数据长度: {len(data4)}")
    else:
        print("✗ PV连接失败")

if __name__ == "__main__":
    try:
        test_pv_timing()
    except KeyboardInterrupt:
        print("\n测试被用户中断")
    except Exception as e:
        print(f"测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()